package com.zhonghe.active4j.function;

import java.util.ArrayList;
import java.util.List;

import com.aliyun.oss.common.utils.StringUtils;

public class SqlFunctionHandler {

	public String getTab(String tableName,String col,String filter) {
		SqlFunctionExcute excute = new SqlFunctionExcute();
		String result = excute.getTab(tableName,StringUtils.join(",", colList(col)),filter.replaceAll("\\[|\\]", "").replace(";", " and "), 
				(x,y,z) -> {
			return "select " + y + " from " + x + " where " + z;
		});
		return result;
	}
	
	private List<String> colList(String col) 
	{
		List<String> re = new ArrayList<>();
		String spiltRules = "\\[|\\]|\\,\\;";
		String[] colArray = col.split(spiltRules);
		for (String s : colArray) {
			if(StringUtils.isNullOrEmpty(s)) 
			{
				continue;
			}
			re.add(s);
		}
		return re;
	}
	
	public String getSqlby(List<String> expList,List<String> by) {
		SqlFunctionExcute excute = new SqlFunctionExcute();
		String result = excute.getTabBy(expList,by, (x,y) -> {
			String sql = "";
			for(int i=0;i<expList.size();i++) {
				List<String> data = new ArrayList<>();
				String spiltRules = "T|\\{|\\}|\\:|\\[|\\]";
				String[] array = expList.get(i).split(spiltRules);
				for (String s : array) {
					if(StringUtils.isNullOrEmpty(s)) 
					{
						continue;
					}
					data.add(s);
				}
				SqlFunctionService service = new SqlFunctionService();
				String s  = service.getSql(data.get(0),data.get(1),data.get(2));
				sql += "(" + s + ")"+(i>=by.size()?"":by.get(i));
			}
			return  "select "+sql+" from dual";
		});
		return result;
	}
}
